package com.liuhuan.service.api;

/**
 * @version 1.0
 * @Author liuhuan
 * @Date 2024/6/28 20:09
 * @客服实现类
 */

import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;


@Component
public class  CrudGeneration {

    private static final String USER_AGENT = "Java-HttpURLConnection/1.0";
    private static final String API_KEY = "sk-6e52620471f54ff0ba86b264c02eb44b";

    public BufferedReader Generation(String UserInput) throws Exception {
        String urlStr = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";

        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + API_KEY);
        connection.setRequestProperty("X-DashScope-SSE", "enable");
        connection.setDoOutput(true);

        String jsonInputString = String.format(
                "{\n" +
                        "    \"model\": \"qwen-turbo\",\n" +
                        "    \"input\": {\n" +
                        "        \"messages\": [\n" +
                        "            {\"role\": \"system\", \"content\": \"你是一个编码助手,能根据实体类自动生成sql文件,控制器层，服务层，数据库层的crud代码，返回格式 按照 sql文件 然后是sql代码 控制器 然后控制器 控制器代码等 其他一句废话也不要说\"},\n" +
                        "            {\"role\": \"user\", \"content\": \"%s\"}\n" +
                        "        ]\n" +
                        "    },\n" +
                        "    \"parameters\": {\n" +
                        "        \"result_format\": \"message\",\n" +
                        "        \"incremental_output\": true\n" +
                        "    }\n" +
                        "}",
                UserInput
        );


        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.write(jsonInputString.getBytes(StandardCharsets.UTF_8));
            wr.flush();
        }

        return new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
    }

}
